package com.alks.function.service.impl.chengKong;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.UserInfoUtil;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.entity.data.entity.CpStitchProcessDetail;
import com.alks.entity.data.entity.PcStitchLotPriceDetail;
import com.alks.entity.data.entity.PcStitchProdDetail;
import com.alks.entity.data.enums.chengkong.DefineEnum;
import com.alks.entity.data.page.PageRecord;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.controller.SysUserController;
import com.alks.function.data.dto.chengKong.Import.StitchVo;
import com.alks.function.data.dto.chengKong.cost.*;
import com.alks.function.data.request.chengKong.*;
import com.alks.function.data.request.chengKong.cost.LotNoCutPriceRequest;
import com.alks.function.data.request.chengKong.cost.UnguidedBodyRequest;
import com.alks.function.data.request.chengKong.cost.generateCutLotNoPriceRequest;
import com.alks.function.mapper.chengKong.CpStitchProcessDetailMapper;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.mapper.chengKong.PcStitchProdDetailMapper;
import com.alks.function.service.chengKong.PcStitchProdDetailService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName: PcStitchBonusReportTempImpl
 * Package: com.alks.function.service.serviceImpl.chengKong
 * Description:
 *
 * @Author 蹇泽阳
 * @Create 2024/2/23 11:02
 * @Version 1.0
 */
@Slf4j
@Service
public class PcStitchProdDetailImpl extends ServiceImpl<PcStitchProdDetailMapper, PcStitchProdDetail> implements PcStitchProdDetailService {
    @Autowired
    private PcStitchProdDetailMapper pcStitchProdDetailMapper;
    @Autowired
    private SysUserController user;
    @Resource
    private CpStitchProcessDetailMapper cpStitchProcessDetailMapper;

    @Override
    @AutoPageAop
    public ResponseInfo<Object> getYieldDetailsList(PcStitchProdDetailRequest request) {
        LambdaQueryWrapper<PcStitchProdDetail> wrapper = new LambdaQueryWrapper<>();

        Map map = new HashMap<>();
        // 查询的sql
        List<pcStitchProdDetailDto> list = pcStitchProdDetailMapper.pcStitchProdDetailList(request);

        //统计订单数量预补数量的sql
        Map<String, BigDecimal> CountSum = pcStitchProdDetailMapper.pcStitchProdDetailCountSum(request);

        PageInfo page = new PageInfo(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        map.put("qytCount",CountSum);
        return  ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo changeYieldDetailsCfm(List<pcStitchProdDetailDto> request, String choose) {
        SysUserTokenDTO dto = UserIdThread.get();
        String userName = dto.getUserName();

        for (pcStitchProdDetailDto pcStitchProdDetail : request) {
            //  0为检核 1为取消检核 2为删除
            if(choose.equals("0")){
                // 如果CfmFlag为Y则不允许检核
                if(pcStitchProdDetail.getCfmFlag() != null && pcStitchProdDetail.getCfmFlag().equals("Y")){
                    return ResponseInfo.error("已检核的数据不允许再次检核");
                }else{
                    pcStitchProdDetailMapper.changeYieldDetailsCfmList(pcStitchProdDetail,userName);
                }
            }

            if(choose.equals("1")){
                // 如果CheckFlag为Y则不允许取消检核
                if(pcStitchProdDetail.getCheckFlag() != null && pcStitchProdDetail.getCheckFlag().equals("Y")){
                    return ResponseInfo.error("已审核的数据不允许取消检核");
                }else {
                    pcStitchProdDetailMapper.cancelYieldDetailsCfmList(pcStitchProdDetail, userName);
                }
            }

            if(choose.equals("2")){
                if(pcStitchProdDetail.getCheckFlag() != null && pcStitchProdDetail.getCheckFlag().equals("Y")){
                    return ResponseInfo.error("已审核的数据不允许删除");
                }else if(pcStitchProdDetail.getCfmFlag() != null && pcStitchProdDetail.getCfmFlag().equals("Y")) {
                    return ResponseInfo.error("已检核的数据不允许删除");
                }else{
                    pcStitchProdDetailMapper.deleteYieldDetailsCfmList(pcStitchProdDetail, userName);
                }
            }
        }
        return ResponseInfo.ok();
    }

    /**
     * 针车选择型体
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo SelectTheTargetVehicleBody(UnguidedBodyRequest request) {
        Map map = new HashMap();
        request.setCompanyId(UserIdThread.get().getCompanyId());
        List<Map<String, String>> cutToolList = pcStitchProdDetailMapper.getCutToolList(request);
        PageInfo pageInfo = new PageInfo(cutToolList);
        map.put("cutToolList",cutToolList);
        map.put("total",pageInfo.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 选择颜色
     * @param styleNo
     * @return
     */
    @Override
    public ResponseInfo ChooseASewingMachineColor(String styleNo) {
        String companyId = UserIdThread.get().getCompanyId();
        return ResponseInfo.ok(pcStitchProdDetailMapper.getStyleToColorList(styleNo,companyId));
    }

    /**
     * 针车工序明细档
     * @param request
     * @return
     */
    @Override
    public ResponseInfo NeedleTurningProcessDetails(StyleNoToColorRequest request) {
        Map map = new HashMap();
        String companyId = UserIdThread.get().getCompanyId();
        List<CpStitchProcessDetailDto> list = pcStitchProdDetailMapper.getCpStitchProcessDetail(request.getStyleNo(),request.getStyleColor(),companyId);
        BigDecimal count=BigDecimal.ZERO;
        for (CpStitchProcessDetailDto t : list) {
            if (t.getPrice() != null){
                count=count.add(t.getPrice());
            }
        }
        map.put("list",list);
        map.put("count",count);
        return ResponseInfo.ok(map);
    }

    /**
     * 针车0检核/1取消检核
     * @param request
     * @param choose
     * @return
     */
    @Override
    public ResponseInfo NeedleCarInspectionAndVerification(StyleNoToColorRequest request, Integer choose) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        switch (choose) {
            case 0:
                if (!StringUtils.isEmpty(request.getCfmFlag())&&request.getCfmFlag().equals(DefineEnum.CHECKOUT_FLAG.getValue())){
                    return ResponseInfo.error("该型体针车工序已经检核,不能再次检核!");
                }
                pcStitchProdDetailMapper.checkOutPcStitchProdDetail(request.getStyleNo(),request.getStyleColor(), DefineEnum.CHECKOUT_FLAG.getValue(), LocalDateTime.now(), UserInfoUtil.getUserInfo().getUserName(),companyId);
                break;
            case 1:
                if (StringUtils.isEmpty(request.getCfmFlag())){
                    return ResponseInfo.error("该型体针车工序未检核,不能取消检核!");
                }
                pcStitchProdDetailMapper.checkOutPcStitchProdDetail(request.getStyleNo(),request.getStyleColor(),null,null,null,companyId);
                break;
            default:
                return ResponseInfo.error("参数错误!");
        }
        return ResponseInfo.ok();
    }

    /**
     * 删除针车型体颜色
     * @param request
     * @return
     */
    @Override
    public ResponseInfo DeleteBodyColor(StyleNoToColorRequest request) {
        if (ObjectUtils.isEmpty(request.getStyleNo())||ObjectUtils.isEmpty(request.getStyleColor())){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        if (!ObjectUtils.isEmpty(request.getCfmFlag())&&request.getCfmFlag().equals(DefineEnum.CHECKOUT_FLAG.getValue())){
            return ResponseInfo.error("该型体针车工序已经检核,不能删除!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        pcStitchProdDetailMapper.deletePcStitchProdDetail(request.getStyleNo(),request.getStyleColor(),companyId);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 整个针车型体删除
     * @param styleNo
     * @return
     */
    @Override
    public ResponseInfo DeleteTheEntireShape(String styleNo) {
        if (ObjectUtils.isEmpty(styleNo)){
            return ResponseInfo.error("型体不能为空!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        List<StyleDetailToFlagDto> list = pcStitchProdDetailMapper.getStyleToColorList(styleNo,companyId);
        if (!ObjectUtils.isEmpty(list)){
            int count=0;
            for (StyleDetailToFlagDto t : list) {
                if (!ObjectUtils.isEmpty(t.getCfmFlag())&&t.getCfmFlag().equals(DefineEnum.CHECKOUT_FLAG.getValue())){
                    count++;
                }
            }
            if (count>0){
                return ResponseInfo.error("已经存在检核记录,不能删除!");
            }
            pcStitchProdDetailMapper.deletePcStitchProdDetail2(styleNo,companyId);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 未导入型体颜色查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo UnguidedBodyColor(UnguidedBodyRequest request) {
        PageRecord<StyleDetailToFlagDto> list = new PageRecord<>();
        request.setCompanyId(UserInfoUtil.getUserInfo().getCompanyId());
        List<StyleDetailToFlagDto> styleToColorToCutToolList = pcStitchProdDetailMapper.getStyleToColorToCutToolList(request);
        PageInfo pageInfo = new PageInfo<>(styleToColorToCutToolList);
        list.setList(styleToColorToCutToolList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    @Resource
    private PcLotHeadMapper pcLotHeadMapper;

    /**
     * 导入针车工序
     * @param file 文件
     * @param style 型体
     * @param color 颜色
     * @return
     */
    @Override
    public ResponseInfo ImportNeedleSewingProcess(MultipartFile file, String style, String color) {
        if (ObjectUtils.isEmpty(style)||ObjectUtils.isEmpty(color)){
            return ResponseInfo.error("型体/颜色不能为空!");
        }
        if (ObjectUtils.isEmpty(file)){
            return ResponseInfo.error("文件不能为空!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        Integer count = pcLotHeadMapper.getStyleToColor(style, color,companyId);
        if (count == null||count == 0) {
            return ResponseInfo.error("该型体颜色不存在!");
        }
        Integer stitchStyleToColor = pcStitchProdDetailMapper.getStitchStyleToColor(style, color,companyId);
        if (stitchStyleToColor != null&&stitchStyleToColor> 0) {
            return ResponseInfo.error("该颜色型体针车工序已建档!");
        }
        File file1 = new File(file.getOriginalFilename());
        try (FileOutputStream fos = new FileOutputStream(file1)) {
            fos.write(file.getBytes());
        } catch (IOException e) {
            log.error("转换文件失败", e);
            return ResponseInfo.error("文件读取失败!");
        }
        List<StitchVo> stitchVos = readExcel(file1);
        if (!ObjectUtils.isEmpty(stitchVos)){
            List<StitchVo> list = stitchVos.stream().filter(data -> data.getSeqNo() != null && data.getProcessName() != null).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(list)){
                Map<String, List<StitchVo>> ProcessName = list.stream().collect(Collectors.groupingBy(StitchVo::getProcessName));
                boolean flag = ProcessName.values().stream()
                        .anyMatch(data -> data.size() > 1);
                if (flag) {
                    return ResponseInfo.error("导入文件存在相同针车工序,导入失败!");
                }

                List<CpStitchProcessDetail> cpStitchProcessDetailList = list.stream().map(t -> {
                    CpStitchProcessDetail detail = new CpStitchProcessDetail();
                    BeanUtil.copyProperties(t, detail);
                    UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
                    detail.setCompanyId(userInfo.getCompanyId());
                    detail.setSysUser(userInfo.getUserName());
                    detail.setStyle(style);
                    detail.setColor(color);
                    detail.setSysDate(LocalDateTime.now());
                    return detail;
                }).collect(Collectors.toList());
                pcStitchProdDetailMapper.addCpStitchProcessDetail(cpStitchProcessDetailList);
            }
        }
        file1.delete();
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 读取excel数据
     * @param file
     * @return
     */
    public List<StitchVo> readExcel(File file) {
        List<StitchVo> dataList = new ArrayList<>();
        FileInputStream fis = null;
        HSSFWorkbook workbook = null;
        try {
            fis = new FileInputStream(file);
            workbook = new HSSFWorkbook(fis);
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
            // 跳过第一行标题
            boolean firstRow = false;
            // 循环遍历每一行
            for (Row row : sheet) {
                if (!firstRow) {
                    firstRow = true;
                    continue;
                }
                StitchVo data = new StitchVo();
                // 循环遍历每一列并设置StitchVo对象的字段值
                int cellIndex = 0;
                for (Cell cell : row) {
                    switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {
                        case NUMERIC:
                            if (cellIndex == 0) {
                                data.setSeqNo(BigDecimal.valueOf(cell.getNumericCellValue()));
                            } else if (cellIndex == 2) {
                                data.setPrice(cell.getNumericCellValue());
                            }
                            break;
                        case STRING:
                            if (cellIndex == 1) {
                                data.setProcessName(cell.getStringCellValue());
                            } else if (cellIndex == 3) {
                                data.setRemark(cell.getStringCellValue());
                            }
                            break;
                        case BOOLEAN:
                            break;
                        case FORMULA:
                            break;
                        case BLANK:
                            break;
                        default:
                    }
                    cellIndex++;
                }
                dataList.add(data);
            }
        } catch (IOException e) {
            log.error("读取文件失败", e);
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    log.error("关闭HSSFWorkbook失败", e);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error("关闭FileInputStream失败", e);
                }
            }
        }
        return dataList;
    }

    /**
     * 选择指令
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo StitchLotNoDetail(LotNoCutPriceRequest request) {
        PageRecord<LotNoDetailDto> list = new PageRecord<>();
        request.setCompanyId(UserIdThread.get().getCompanyId());
        List<LotNoDetailDto> styleToColorToCutToolList = pcStitchProdDetailMapper.getStitchLotNoDetail(request);
        PageInfo pageInfo = new PageInfo<>(styleToColorToCutToolList);
        list.setList(styleToColorToCutToolList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 1 生成指令单价 2重新生成指令单价
     * @param request
     * @param choose
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo GenerateInstructionProcessUnitPrice(generateCutLotNoPriceRequest request, Integer choose) {
        if (StringUtils.isAnyBlank(request.getLotNo(), request.getStyle(), request.getColor())) {
            return ResponseInfo.error("指令/型体/颜色不能为空!");
        }
        switch (choose) {
            case 1:
                if (StringUtils.isBlank(request.getCfmFlag())) {
                    return ResponseInfo.error("存在型体单价未建档的指令记录,不能处理!");
                }
                addPcStitchLotPriceDetail(request);
                break;
            case 2:
                if (!StringUtils.isEmpty(request.getCfmFlag())&&DefineEnum.CHECKOUT_FLAG.getValue().equals(request.getCfmFlag())) {
                    return ResponseInfo.error("财务已经检核,不能处理!");
                }
                addPcStitchLotPriceDetail(request);
                break;
            default:
                return ResponseInfo.error("参数错误!");
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 针车指令新增/重新生成
     * @param request
     */
    private void addPcStitchLotPriceDetail(generateCutLotNoPriceRequest request) {
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        List<CpStitchProcessDetailDto> list = pcStitchProdDetailMapper.getCpStitchProcessDetail(request.getStyle(), request.getColor(), userInfo.getCompanyId());
        if (!ObjectUtils.isEmpty(list)){
            List<PcStitchLotPriceDetail> pcStitchLotPriceDetailList = list.stream().map(t -> {
                PcStitchLotPriceDetail entity = new PcStitchLotPriceDetail();
                BeanUtil.copyProperties(t, entity);
                entity.setCompanyId(userInfo.getCompanyId());
                entity.setSysUser(userInfo.getUserName());
                entity.setSysDate(LocalDateTime.now());
                entity.setLotNo(request.getLotNo());
                entity.setStyle(request.getStyle());
                entity.setColor(request.getColor());
                return entity;
            }).collect(Collectors.toList());
            pcStitchProdDetailMapper.deletePcStitchLotProdDetail(request.getLotNo(),userInfo.getCompanyId());
            pcStitchProdDetailMapper.addPcStitchLotProdDetail(pcStitchLotPriceDetailList);
        }else {
            pcStitchProdDetailMapper.deletePcStitchLotProdDetail(request.getLotNo(),userInfo.getCompanyId());
        }
    }

    /**
     * 针车指令查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getLotNoStitchDetail(LotNoCutPriceRequest request) {
        PageRecord<LotNoDetailDto> list = new PageRecord<>();
        request.setCompanyId(UserIdThread.get().getCompanyId());
        List<LotNoDetailDto> styleToColorToCutToolList = pcStitchProdDetailMapper.getLotNoStitchDetail(request);
        PageInfo pageInfo = new PageInfo<>(styleToColorToCutToolList);
        list.setList(styleToColorToCutToolList);
        list.setTotal(pageInfo.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 针车型体单价明细
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getLotNoStitchDetailList(LotNoRequest request) {
        HashMap map=new HashMap();
        String companyId = UserIdThread.get().getCompanyId();
        List<CpStitchProcessDetailDto> list = pcStitchProdDetailMapper.getLotNoStitchDetailList(request.getLotNo(),companyId);
        //针车单价总数
        BigDecimal countCutPrice = BigDecimal.ZERO;
        if (!ObjectUtils.isEmpty(list)){
            for (CpStitchProcessDetailDto t : list) {
                if (!ObjectUtils.isEmpty(t.getPrice())) {
                    countCutPrice=countCutPrice.add(t.getPrice());
                }
            }
        }
        map.put("list",list);
        map.put("totalCutPrice",countCutPrice);
        return ResponseInfo.ok(map);
    }

    @Override
    public int copyDetail(List<StitchStyleProcessDto> stitchStyles, String style, String color) {
        String companyId = UserIdThread.get().getCompanyId();
        LambdaQueryWrapper<CpStitchProcessDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CpStitchProcessDetail::getCompanyId, companyId);
        queryWrapper.eq(CpStitchProcessDetail::getStyle, style);
        queryWrapper.eq(CpStitchProcessDetail::getColor, color);
        List<CpStitchProcessDetail> details = cpStitchProcessDetailMapper.selectList(queryWrapper);
        if (details.isEmpty()) {
            throw new ServiceErrorException(String.format("选择型体【%s】颜色【%s】不存在工序信息", style, color));
        }
        int tag = 0;
        LocalDateTime now = LocalDateTime.now();
        for (StitchStyleProcessDto stitchStyle : stitchStyles) {

            CpStitchProcessDetail tempSPD = new CpStitchProcessDetail();
            tempSPD.setCompanyId(companyId);
            tempSPD.setStyle(stitchStyle.getStyle());
            tempSPD.setColor(stitchStyle.getColor());

            List<StitchStyleProcessDto> tempList = this.cpStitchProcessDetailMapper.selectByStyleAndColor(tempSPD);
            if (!tempList.isEmpty()) {
                throw new ServiceErrorException(String.format("型体【%s】颜色【%s】工序已存在",
                        stitchStyle.getStyle(), stitchStyle.getColor() ));
            }
            for (CpStitchProcessDetail spd1 : details) {
                CpStitchProcessDetail temp = new CpStitchProcessDetail();
                temp.setCompanyId(companyId);
                temp.setSeqNo(spd1.getSeqNo());
                temp.setPrice(spd1.getPrice());
                temp.setProcessName(spd1.getProcessName());
                temp.setSysDate(now);
                temp.setSysUser(UserIdThread.get().getUserName());

                temp.setStyle(stitchStyle.getStyle());
                temp.setColor(stitchStyle.getColor());
                tag += cpStitchProcessDetailMapper.insert(temp);
            }
        }
        return tag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int copyDetailByProcess(List<StitchStyleProcessDto> stitchStyles, String style, String color, List<Integer> seqNos) {
        String companyId = UserIdThread.get().getCompanyId();
        LambdaQueryWrapper<CpStitchProcessDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CpStitchProcessDetail::getCompanyId, companyId);
        queryWrapper.eq(CpStitchProcessDetail::getStyle, style);
        queryWrapper.eq(CpStitchProcessDetail::getColor, color);
        queryWrapper.in(CpStitchProcessDetail::getSeqNo, seqNos);
        List<CpStitchProcessDetail> details = cpStitchProcessDetailMapper.selectList(queryWrapper);
        if (details.isEmpty()) {
            throw new ServiceErrorException(String.format("未选择型体【%s】颜色【%s】的工序信息", style, color));
        }
        int tag = 0;
        for (StitchStyleProcessDto stitchStyle : stitchStyles) {
            queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CpStitchProcessDetail::getCompanyId, companyId);
            queryWrapper.eq(CpStitchProcessDetail::getStyle, stitchStyle.getStyle());
            queryWrapper.eq(CpStitchProcessDetail::getColor, stitchStyle.getColor());
            queryWrapper.orderByAsc(CpStitchProcessDetail::getSeqNo);

            List<CpStitchProcessDetail> tempList = cpStitchProcessDetailMapper.selectList(queryWrapper);
            int maxSeqNo = 1;
            if (!tempList.isEmpty()) {
                CpStitchProcessDetail lastOne = tempList.get(tempList.size() - 1);
                maxSeqNo = lastOne.getSeqNo().intValue();
            }

            for (CpStitchProcessDetail spd1 : details) {
                int segNo = 0;
                if (!tempList.isEmpty()) {
                    long exist = tempList.stream().filter(e -> spd1.getProcessName().equals(e.getProcessName())).count();
                    if (exist > 0) {
                        throw new ServiceErrorException("存在重复的记录，无法执行操作!!!");
                    }
                    // 当前阶段的工序不存在直接插入，存在追加到最后一个
                    exist = tempList.stream().filter(e -> e.getSeqNo().intValue() == stitchStyle.getSeqNo()).count();
                    if (exist == 0) {
                        segNo = stitchStyle.getSeqNo();
                    } else {
                        ++maxSeqNo;
                        segNo = maxSeqNo;
                    }
                }
                CpStitchProcessDetail temp = new CpStitchProcessDetail();
                temp.setCompanyId(companyId);
                temp.setSeqNo(BigDecimal.valueOf(segNo));
                temp.setPrice(spd1.getPrice());
                temp.setProcessName(spd1.getProcessName());
                temp.setSysDate(LocalDateTime.now());
                temp.setSysUser(UserIdThread.get().getUserName());
                temp.setRemark(spd1.getRemark());

                temp.setStyle(stitchStyle.getStyle());
                temp.setColor(stitchStyle.getColor());
                tag += cpStitchProcessDetailMapper.insert(temp);
            }
        }
        return tag;
    }

    @Override
    @AutoPageAop
    public ResponseInfo stitchProcessDealList(StitchProcessPageReq request) {
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        Map<String, Object> map = new HashMap<>();
        List<StitchStyleProcessDto> list = cpStitchProcessDetailMapper.searchDealUnCfmList(request);
        PageInfo<StitchStyleProcessDto> page = new PageInfo<>(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    @Override
    @AutoPageAop
    public ResponseInfo stitchProcessUnDealList(StitchProcessPageReq request) {
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        Map<String, Object> map = new HashMap<>();
        List<StitchStyleProcessDto> list = cpStitchProcessDetailMapper.searchUndealList(request);
        PageInfo<StitchStyleProcessDto> page = new PageInfo<>(list);
        map.put("total",page.getTotal());
        map.put("list",list);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo removeProcess(String style, String color, List<Integer> seqNos) {
        String companyId = UserIdThread.get().getCompanyId();
        LambdaUpdateWrapper<CpStitchProcessDetail> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CpStitchProcessDetail::getCompanyId, companyId);
        updateWrapper.eq(CpStitchProcessDetail::getStyle, style);
        updateWrapper.eq(CpStitchProcessDetail::getColor, color);
        updateWrapper.in(CpStitchProcessDetail::getSeqNo, seqNos);
        return ResponseInfo.ok(cpStitchProcessDetailMapper.delete(updateWrapper) > 0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseInfo saveProcess(StitchProcessSaveReq saveReq) {
        String companyId = UserIdThread.get().getCompanyId();
        LambdaQueryWrapper<CpStitchProcessDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CpStitchProcessDetail::getCompanyId, companyId);
        queryWrapper.eq(CpStitchProcessDetail::getStyle, saveReq.getStyle());
        queryWrapper.eq(CpStitchProcessDetail::getColor, saveReq.getColor());
        List<CpStitchProcessDetail> processList = cpStitchProcessDetailMapper.selectList(queryWrapper);
        Map<Integer, CpStitchProcessDetail> processMap = processList.stream().collect(Collectors.toMap(e -> e.getSeqNo().intValue(), e -> e));

        if (!saveReq.getItems().isEmpty()) {
            Map<Integer, Long> mapGroup = saveReq.getItems().stream()
                    .collect(Collectors.groupingBy(StitchProcessSaveReq.Item::getSeqNo, Collectors.counting()));
            if (mapGroup.entrySet().stream().anyMatch(entry -> entry.getValue() > 1)) {
                throw new ServiceErrorException("存在重复的序号，无法执行操作!!!");
            }
            for (StitchProcessSaveReq.Item item : saveReq.getItems()) {
                if (processMap.containsKey(item.getSeqNo())) {
                    LambdaUpdateWrapper<CpStitchProcessDetail> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(CpStitchProcessDetail::getCompanyId, companyId);
                    updateWrapper.eq(CpStitchProcessDetail::getStyle, saveReq.getStyle());
                    updateWrapper.eq(CpStitchProcessDetail::getColor, saveReq.getColor());
                    updateWrapper.eq(CpStitchProcessDetail::getSeqNo, item.getSeqNo());

                    updateWrapper.set(CpStitchProcessDetail::getProcessName, item.getProcessName());
                    updateWrapper.set(CpStitchProcessDetail::getPrice, item.getPrice());
                    updateWrapper.set(CpStitchProcessDetail::getRemark, item.getRemark());

                    cpStitchProcessDetailMapper.update(null, updateWrapper);
                } else {
                    long exist = processList.stream().filter(e -> item.getProcessName().equals(e.getProcessName())).count();
                    if (exist > 0) {
                        throw new ServiceErrorException("存在重复的记录，无法执行操作!!!");
                    }

                    CpStitchProcessDetail temp = new CpStitchProcessDetail();
                    temp.setCompanyId(companyId);
                    temp.setSeqNo(BigDecimal.valueOf(item.getSeqNo()));
                    temp.setProcessName(item.getProcessName());
                    temp.setPrice(item.getPrice());
                    temp.setRemark(item.getRemark());
                    temp.setSysDate(LocalDateTime.now());
                    temp.setSysUser(UserIdThread.get().getUserName());

                    temp.setStyle(saveReq.getStyle());
                    temp.setColor(saveReq.getColor());
                    cpStitchProcessDetailMapper.insert(temp);
                }
            }
        }
        return ResponseInfo.ok(true);
    }
}
